<template>
  <div class="login-container">
    <h2 class="login-title">{{ t("loginPage.title") }}</h2>
    <el-form
      ref="loginForm"
      :model="form"
      :rules="rules"
      label-width="0"
      @submit.prevent="onSubmit"
      class="login-form"
    >
      <el-form-item prop="username">
        <el-input
          v-model="form.username"
          :placeholder="t('loginPage.usernamePlaceholder')"
          :prefix-icon="User"
          size="large"
          class="login-username"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          type="password"
          :placeholder="t('loginPage.passwordPlaceholder')"
          show-password
          :prefix-icon="Lock"
          size="large"
          class="login-password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-button" native-type="submit">
          {{ t("loginPage.loginButton") }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { loginApi } from "../api";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "../stores";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const store = useStore();
// 表单数据
const form = ref({
  username: "",
  password: "",
});
const router = useRouter();
const route = useRoute();
// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: t("loginPage.rules.username"), trigger: "blur" },
    {
      min: 3,
      max: 12,
      message: t("loginPage.rules.usernameLength"),
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: t("loginPage.rules.password"), trigger: "blur" },
    {
      min: 6,
      max: 16,
      message: t("loginPage.rules.passwordLength"),
      trigger: "blur",
    },
  ],
});

// 表单引用
const loginForm = ref(null);

// 提交表单
const onSubmit = () => {
  loginForm.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await loginApi(form.value);
        localStorage.setItem("token", res.token);
        store.userInfo = res.user;
        store.userInfo.avatar = `${import.meta.env.VITE_BASE_URL}api/user/avatar/${store?.userInfo?.id}?timestamp=${Date.now()}`;
        if (route.query.redirect) {
          router.replace(route.query.redirect);
        } else {
          router.replace("/home");
        }
      } catch (error) {
        console.error("登录失败:", error);
      }
    } else {
      ElMessage.warning("请检查表单输入");
    }
  });
};
</script>
